import { getToken, setToken, removeToken } from '@/utils/auth'
import { login, getUserInfo } from '@/api/user'
import { constantRoutes, resetRouter } from '@/router'
const state = {
  // 获取token
  token: getToken(),
  userInfo: '',
  routes: constantRoutes
}
const mutations = {
  setToken(state, token) {
    state.token = token
    // 将token设置到cookies
    setToken(token)
  },
  removeToken(state) {
    // 将token从cookies中移除
    removeToken()
    state.token = null
  },
  setUserInfo(state, data) {
    state.userInfo = data
  },
  setRoutes(state, newRoutes) {
    state.routes = [...constantRoutes, ...newRoutes]
  }
}
const actions = {
  async login(context, data) {
    const token = await login(data)
    context.commit('setToken', token)
  },
  async getUserInfo(context) {
    const result = await getUserInfo()
    context.commit('setUserInfo', result)
    return result
  },
  logout(context) {
    // 清除token
    context.commit('removeToken')
    // 设置用户信息为空对象
    context.commit('setUserInfo', {})
    // 重置路由
    resetRouter()
  }
}
export default {
  namespaced: true,
  state,
  mutations,
  actions
}
